<template>
    <div class="container">
      <div class="search-box">
        <el-form :model="search" label-width="80px" class="flex" style="align-items: center;">
          <el-form-item label="协议书号">
            <el-input v-model="search.likeWords" placeholder="请输入" clearable size="small"></el-input>
          </el-form-item>
          <el-form-item label="客户名称" class="ml16">
            <el-select
                v-model="search.CustomerCode"
                placeholder="请选择客户名称"
                clearable
                style="width: 100%"
                filterable
                size="small"
                @change="handleCustomerChange"
              >
                <el-option
                  v-for="item in customerList"
                  :key="item.customerCode"
                  :label="item.customerName"
                  :value="item.customerCode"
                />
              </el-select>
          </el-form-item>
          <el-form-item label="产品名称">
            <el-select
                v-model="search.ProductCode"
                placeholder="产品名称"
                clearable
                style="width: 100%"
                filterable
                size="small"
              >
                <el-option
                  v-for="item in productList"
                  :key="item.productCode"
                  :label="item.productName"
                  :value="item.productCode"
                />
              </el-select>
          </el-form-item>
              <el-form-item label="日期范围" class="ml16">
                <el-date-picker
                  v-model="valueDate"
                  style="width: 100%"
                  size="small"
                  type="daterange"
                  range-separator="-"
                  value-format="yyyy-MM-dd"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  @change="handleDateChange"
                >
                </el-date-picker>
              </el-form-item>
              
              <div>
                  <el-button
                    type="primary"
                    size="small"
                    icon="el-icon-search"
                    style="margin-left: 30px"
                    :loading="searchLoading"
                    @click="handleSearch"
                    >搜索</el-button
                  >
                  <el-button size="small" icon="el-icon-download" @click="handleDownloadExcel">导出excel</el-button>
                  <!-- <el-button size="small" icon="el-icon-download" :loading="downLoading" @click="downloadFile">导出数据</el-button> -->
              </div>
        </el-form>
      </div>
      <div class="d_main flex1">
        <!-- 操作区 S-->
        <!-- 操作区 E-->
        <!-- 表格操作区 S-->
        <div class="d_tableOperation">
          <div class="d_condition"></div>
          <div class="d_set">
            <div @click="Refresh"><i class="d_icon el-icon-refresh-right" /></div>
            <div class="setting flex">
              <HeadSeting
                :list-data.sync="tableHead"
                :table-code="$config.outstockreportlist"
                @reset="getTableHead"
              />
            </div>
          </div>
        </div>
        <!-- 表格操作区 E-->
        <!--table板块-->
        <div ref="tableCon" class="tableCon expandBox">
          <el-table
            v-show="tableHead.length > 0"
            id="tableId"
            ref="multipleTable"
            v-loading="searchLoading"
            :data="allMaterirls"
            :height="tableHeight || 'auto'"
            border
            fit
            style="width: 100%"
            @header-dragend="surverWidth"
          >
            <template v-for="(fruit, index) in tableHead">
              <el-table-column
                v-if="fruit.visible"
                :key="index"
                :label="fruit.columnName"
                :min-width="fruit.columnWidth || 90"
                :prop="fruit.columnCode"
                show-overflow-tooltip
                :fixed="fruit.isFloat ? 'left' : false"
              >
                <template slot-scope="scope">
                  <el-button
                    v-if="fruit.columnCode === 'getMaterialBillNo'"
                    type="text"
                    @click="checkProductList(scope.row)"
                  >
                    {{ scope.row[fruit.columnCode] }}</el-button
                  >
                  <div
                    v-else-if="fruit.columnCode === 'getMaterialBillStateName'"
                    class="flex"
                  >
                    <template v-if="scope.row.getMaterialBillState === 0">
                      <span class="mr5 spot" style="background: #3f61f1" />{{
                        scope.row[fruit.columnCode]
                      }}
                    </template>
                    <template
                      v-else-if="
                        scope.row.getMaterialBillState === 1 ||
                        scope.row.getMaterialBillState === 3
                      "
                    >
                      <span class="mr5 spot" style="background: #67c23a" />{{
                        scope.row[fruit.columnCode]
                      }}
                    </template>
                    <template v-else>
                      <span class="mr5 spot" style="background: #999aaa" />{{
                        scope.row[fruit.columnCode]
                      }}
                    </template>
                  </div>
                  <div
                    v-else-if="fruit.columnCode === 'outStockStateName'"
                    class="flex"
                  >
                    <template v-if="scope.row.outStockState === 0">
                      <span class="mr5 spot" style="background: #3f61f1" />{{
                        scope.row[fruit.columnCode]
                      }}
                    </template>
                    <template v-else-if="scope.row.outStockState === 1">
                      <span class="mr5 spot" style="background: #67c23a" />{{
                        scope.row[fruit.columnCode]
                      }}
                    </template>
                    <template v-else>
                      <span class="mr5 spot" style="background: #e13335" />{{
                        scope.row[fruit.columnCode]
                      }}
                    </template>
                  </div>
                  <template v-else>
                    {{ scope.row[fruit.columnCode] }}
                  </template>
                </template></el-table-column
              >
            </template>
          </el-table>
          <!-- 骨架屏     -->
          <div v-if="tableHead.length == 0" class="p16">
            <el-skeleton :rows="6" animated />
          </div>
        </div>
        <!-- 分页 S-->
        <div class="d_pag">
          <pagination
            :total="total || 0"
            :page.sync="search.pageIndex"
            :limit.sync="search.pageSize"
            @pagination="getAllMaterils"
          />
        </div>
      </div>
    </div>
  </template>
  <script>
  import { arraySort } from "@/utils";
  import HeadSeting from "@/components/HeadSeting";
  import Pagination from "@/components/Pagination";
  import { mapGetters } from "vuex";
  import FileSaver from "file-saver";
import XLSX from "xlsx";
  import {fileExport} from "@/utils/index"
  export default {
    name: "outWarehouse",
    components: {
      Pagination,
      HeadSeting,
    },
    data() {
      return {
        searchLoading:false,  //表格加载层
        downLoading:false,  //下载文件按钮加载层
        valueDate: "",
        allMaterirls: [],
        tableHeight: null,
        query: {
          groupCode: "", //分组代码，空值查询全部
          categoryCode: "", //	分类代码，空值查询全部
          supplierCode: "", //供应商代码，空值查询全部
          goodsCode: "", //基础物料代码，空值查询全部
          likeWords: "", //查询关键字，空值查询全部
        },
        customerList:[],
        productList:[],
        // 搜索条件
        search: {
          pageIndex: 1,
          pageSize: 30,
          likeWords: "",
          isShowDisabled: 0,
          CustomerCode:'',
          ProductCode:'',
          beginTime: "", //入库日期范围-开始时间
          endTime: "", //	入库日期范围-结束时间
          QueryDataBaseFiled:"XieYiShuHao",
        },

        // 搜索条件
        productSearch: {
          pageIndex: 1,
          pageSize: 9999,
          queryDataBaseFiled: "",
          likeWords: "",
          isShowDisabled: 1,
          state: 0,
          customerCode: "",
        },
        total: 0, // 总条数
        tableHead: [], // 表格表头
      };
    },
    computed: {
      ...mapGetters(["name", "userInfo"]),
    },
    created() {
      //  所有列表数据
      this.getAllMaterils();
      // 表格得表头
      this.getTableHead();
      this.getQueryPageCustomerList()
      this.getProductList()
    },
    mounted() {
      // 表格高度
      this.calHeight();
      console.log(this.ProductForm);
    },
    updated() {
      this.$nextTick(() => {
        this.$refs.multipleTable.doLayout();
      });
    },
    methods: {
      //客户名称选择事件
      handleCustomerChange(e){
        this.productSearch.customerCode = e
        this.getProductList()
      },

      // 获取产品列表
      getProductList() {
        const parmas = this.productSearch;
        this.$api.business
          .GetProductBriefList(parmas)
          .then((res) => {
            this.productList = res;
          })
      },
  
      // 获取客户列表
      getQueryPageCustomerList() {
        const cusSearch = {
          likeWords: "",
          settlementWay: 0,
          belongToSalesman: "",
          IsEnabled: 1,
          pageIndex: 1,
          pageSize: 9999,
        };
        this.$api.business.QueryPageCustomerList(cusSearch).then((res) => {
          this.customerList = res.list;
        });
      },

       //导出excel
  handleDownloadExcel() {
      var xlsxParam = { raw: true };
      var fileName = `${this.$route.meta.title}.xlsx`
      // let tables = document.querySelector('#tableId').cloneNode(true) // 重点
      // let fixed  = tables.querySelector(".el-table__fixed")
      // tables.removeChild(fixed) // 重点
      var wb = XLSX.utils.table_to_book(
        document.querySelector("#tableId"),
        xlsxParam
      );

      /* 获取二进制字符串作为输出 */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          //Blob 对象表示一个不可变、原始数据的类文件对象。
          //Blob 表示的不一定是JavaScript原生格式的数据。
          //File 接口基于Blob，继承了 blob 的功能并将其扩展使其支持用户系统上的文件。
          //返回一个新创建的 Blob 对象，其内容由参数中给定的数组串联组成。
          new Blob([wbout], { type: "application/octet-stream" }),
          //设置导出文件名称
          fileName
        );
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      return wbout;
    },
  
      //日期范围选择事件
      handleDateChange() {
        if (this.valueDate) {
          this.search.beginTime = this.valueDate[0];
          this.search.endTime = this.valueDate[1];
        } else {
          this.search.beginTime = "";
          this.search.endTime = "";
        }
      },
  
      //导出数据
      downloadFile(){
        this.downLoading = true
        this.$api.report.ExportOutStockReportsDataToExcel(this.search).then((res) => {
          fileExport(res,'物料出库导出数据','xlsx')
          this.downLoading = false
        });
      },
  
      // 保存表头样式变化
      saveHead(newArray) {
        const parmas = newArray;
        setTimeout(() => {
          this.$api.common.saveTableStyle(parmas).then(() => {});
        }, 300);
      },
      // 保存表头列宽度
      surverWidth(newWidth, oldWidth, column) {
        setTimeout(() => {
          const heads = [...this.tableHead];
          heads.forEach((item) => {
            if (item.columnCode === column.property) {
              item.columnWidth = column.width;
              return;
            }
          });
          this.saveHead(heads);
        }, 100);
      },
      // 表格最大高度
      calHeight() {
        this.$nextTick(() => {
          const rect = this.$refs.tableCon.getBoundingClientRect();
          console.log(rect.height)
          this.tableHeight = rect.height;
        });
      },
      // ，清除所有查询条件
      Refresh() {
        this.search = this.$options.data().search;
        this.getAllMaterils();
      },
      // 获取表格表头
      getTableHead() {
        const parmas = {
          tableCode: this.$config.finishedProductInStock,
        };
        this.$api.common.getAllTableHead(parmas).then((res) => {
          console.log(res);
          res.sort(arraySort("columnSort"));
          this.tableHead = res;
        });
      },
  
      //搜索
      handleSearch(){
        this.search.pageIndex = 1
        this.getAllMaterils()
      },
  
      // 所有列表数据
      getAllMaterils() {
        const parmas = this.search;
        this.searchLoading = true;
        this.$api.report
          .PageQueryFinishedProductInStockReport(parmas)
          .then((res) => {
           setTimeout(()=>{console.log(res)},2000) 
            this.allMaterirls = res.list;
            console.log(this.allMaterirls)
            this.total = res.totalCount;
            this.searchLoading = false;
          })
          .catch(() => {
            this.searchLoading = false;
          });
      },
    },
  };
  </script>
  <style lang="scss" scoped>
  .search-box {
    padding: 14px 16px 0 0;
    margin-bottom: 10px;
    display: flex;
    height: 78px;
    background: #ffffff;
    border-radius: 4px;
    border: 1px solid #e6e6e6;
    .el-form-item {
      margin-bottom: 0 !important;
    }
  }

  .container {
    padding: 10px;
    display: flex;
    flex-direction: column;
    height: 100%;
  }
  .permangeRg {
    border: 1px solid #e6e6e6;
    background: #fff;
    height: 100%;
  
    .mainTT {
      font-size: 16px;
      font-weight: bold;
      width: 100%;
      padding: 18px 16px;
      padding-bottom: 0;
    }
  }
  .addWuliaoBox {
    padding: 10px 16px;
  
    .tableBox {
      margin-top: 16px;
      border: 1px solid #e6e6e6;
      border-bottom: none;
      border-radius: 8px 8px 0 0;
      overflow: hidden;
  
      .tt {
        height: 38px;
        line-height: 38px;
        padding-left: 16px;
        background: #f7f8fa;
        border-radius: 8px 8px 0 0;
      }
    }
  }
  
  .subTip {
    border-bottom: 1px #e6e6e6 solid;
    background: #f5f6f9;
    padding: 8px 16px;
  }
  </style>
  